package com.hiyee.api.interceptors;

import com.hiyee.exception.GraceException;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.utils.IPUtil;
import com.hiyee.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通行证拦截器
 *
 * @author WangBin
 */
public class PassportInterceptor implements HandlerInterceptor {
    @Autowired
    public RedisOperator redisOperator;

    public static final String REDIS_KEY_MOBILE_SMS_CODE_LOCK = "hiyee:mobile:sms_code:lock";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 根据 IP 限制客户 60 秒内只能获取一次验证码
        String ip = IPUtil.getRequestIp(request);

        // key 是否存在
        boolean exist = redisOperator.keyIsExist(REDIS_KEY_MOBILE_SMS_CODE_LOCK + ip);
        if(exist) {
            GraceException.display(ResponseStatusEnum.SMS_SEND_CODE_BUSY);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
